<template>
  <Dialog
    class="slim-dialog"
    :title="t('studentPaper.view.title')"
    v-model="dialogVisible"
    width="950"
  >
    <template
      v-if="
        !edit &&
        type === 'edit' &&
        (formData.reviewStatus === '草稿' ||
          formData.reviewStatus === '已撤回' ||
          formData.reviewStatus === '已拒绝')
      "
    >
      <el-button class="mb-[16px]" type="primary" plain @click="handleEdit" :disabled="formLoading">
        <Icon icon="ep:edit" />
        {{ t('studentPaper.view.clickEdit') }}
      </el-button>
    </template>
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-position="top"
      @submit.prevent
    >
      <el-descriptions v-loading="formLoading" :column="1" border label-width="230">
        <el-descriptions-item
          label-class-name="is--asterisk"
          :label="t('studentPaper.fields.paperTitle')"
        >
          <el-form-item prop="paperTitle">
            <EditInput
              v-model="formData.paperTitle"
              :placeholder="t('common.inputTextPlaceholder') + t('studentPaper.fields.paperTitle')"
            />
          </el-form-item>
        </el-descriptions-item>
        <el-descriptions-item
          label-class-name="is--asterisk"
          :label="t('studentPaper.fields.attachment')"
        >
          <el-form-item prop="attachment">
            <IMRUpload
              v-model="formData.attachment"
              :file-type="['pdf']"
              :file-size="3"
              :limit="1"
              :disabled="!edit"
            />
          </el-form-item>
        </el-descriptions-item>
        <!--            <el-descriptions-item :label="t('studentPaper.fields.paperTime')" >-->
        <!--              <el-form-item prop="paperTime">-->
        <!--                <EditDate-->
        <!--                  v-model="formData.paperTime"-->
        <!--                  :placeholder="-->
        <!--                    t('common.selectTextPlaceholder') + t('studentPaper.fields.paperTime')-->
        <!--                  "-->
        <!--                />-->
        <!--              </el-form-item>-->
        <!--            </el-descriptions-item>-->
        <el-descriptions-item
          label-class-name="is--asterisk"
          :label="t('studentPaper.fields.paperType')"
        >
          <el-form-item prop="paperType">
            <EditDict
              :dict-type="DICT_TYPE.RESEARCH_PAPER_TYPE"
              v-model="formData.paperType"
              :placeholder="t('common.selectTextPlaceholder') + t('studentPaper.fields.paperType')"
            />
          </el-form-item>
        </el-descriptions-item>
        <!--            <el-descriptions-item :label="t('studentPaper.fields.paperClass')" >-->
        <!--              <el-form-item prop="paperClass">-->
        <!--                <EditDict-->
        <!--                  :dict-type="DICT_TYPE.RESEARCH_PAPER_CLASS"-->
        <!--                  v-model="formData.paperClass"-->
        <!--                  :placeholder="-->
        <!--                    t('common.selectTextPlaceholder') + t('studentPaper.fields.paperClass')-->
        <!--                  "-->
        <!--                />-->
        <!--              </el-form-item>-->
        <!--            </el-descriptions-item>-->
        <el-descriptions-item
          label-class-name="is--asterisk"
          :label="t('studentPaper.fields.primaryAuthor')"
        >
          <el-form-item prop="primaryAuthor">
            <EditInput
              v-model="formData.primaryAuthor"
              :placeholder="
                t('common.inputTextPlaceholder') + t('studentPaper.fields.primaryAuthor')
              "
            />
          </el-form-item>
        </el-descriptions-item>
        <el-descriptions-item
          label-class-name="is--asterisk"
          :label="t('studentPaper.fields.personalRanking')"
        >
          <el-form-item prop="personalRanking">
            <EditDict
              :dict-type="DICT_TYPE.RESEARCH_PERSONAL_RANKING"
              v-model="formData.personalRanking"
              :placeholder="
                t('common.selectTextPlaceholder') + t('studentPaper.fields.personalRanking')
              "
              :input-tips="t('studentPaper.inputTips.personalRanking')"
            />
          </el-form-item>
        </el-descriptions-item>
        <el-descriptions-item
          v-if="formData.personalRanking === '并列第一'"
          label-class-name="is--asterisk"
          :label="t('studentPaper.fields.parallelCount')"
        >
          <el-form-item prop="parallelCount">
            <EditInput v-model="formData.parallelCount" style="width: 150px">
              <template #prepend>{{ t('studentPaper.inputTips.parallelCountPrefix') }}</template>
              <template #append>{{ t('studentPaper.inputTips.parallelCountSuffix') }}</template>
            </EditInput>
          </el-form-item>
        </el-descriptions-item>
        <el-descriptions-item
          v-if="formData.personalRanking === '并列第一'"
          label-class-name="is--asterisk"
          :label="t('studentPaper.fields.parallelRanking')"
        >
          <el-form-item prop="parallelRanking">
            <EditInput v-model="formData.parallelRanking" style="width: 150px">
              <template #prepend>{{ t('studentPaper.inputTips.parallelRankingPrefix') }}</template>
              <template #append>{{ t('studentPaper.inputTips.parallelRankingSuffix') }}</template>
            </EditInput>
          </el-form-item>
        </el-descriptions-item>
        <el-descriptions-item
          label-class-name="is--asterisk"
          :label="t('studentPaper.fields.casRanking')"
        >
          <el-form-item prop="casRanking">
            <EditDict
              :dict-type="DICT_TYPE.RESEARCH_USTC_RANKING"
              v-model="formData.casRanking"
              :placeholder="
                t('common.selectTextPlaceholder') +
                t('studentPaper.fields.casRanking') +
                t('studentPaper.inputTips.casRanking')
              "
            />
          </el-form-item>
        </el-descriptions-item>
        <el-descriptions-item
          label-class-name="is--asterisk"
          :label="t('studentPaper.fields.imrRanking')"
        >
          <el-form-item prop="imrRanking">
            <EditDict
              :dict-type="DICT_TYPE.RESEARCH_IMR_RANKING"
              v-model="formData.imrRanking"
              :placeholder="
                t('common.selectTextPlaceholder') +
                t('studentPaper.fields.imrRanking') +
                t('studentPaper.inputTips.casRanking')
              "
            />
          </el-form-item>
        </el-descriptions-item>
        <el-descriptions-item
          label-class-name="is--asterisk"
          :label="t('studentPaper.fields.journalName')"
        >
          <el-form-item prop="journalId">
            <div class="flex w-1/1 gap-10px">
              <PositiveJournalSelect
                v-if="!manualInput"
                class="flex-grow-1"
                v-model="formData.journalId"
                :placeholder="
                  t('common.selectTextPlaceholder') +
                  t('studentPaper.fields.journalName') +
                  t('studentPaper.inputTips.journalSwitch')
                "
                @selected="journalSelected"
              />
              <EditInput
                v-else
                v-model="formData.journalName"
                :placeholder="
                  t('common.inputTextPlaceholder') + t('studentPaper.fields.journalName')
                "
                @input="handleJournalManualInput"
              />
              <el-button v-if="edit" @click="handleSwitchJournal">
                <span v-if="!manualInput">{{ t('studentPaper.inputTips.journalManual') }}</span>
                <span v-else>{{ t('studentPaper.inputTips.journalSelect') }}</span>
              </el-button>
            </div>
          </el-form-item>
        </el-descriptions-item>
        <el-descriptions-item
          label-class-name="is--asterisk"
          :label="t('studentPaper.fields.journalIssn')"
        >
          <el-form-item prop="journalIssn">
            <EditInput
              v-model="formData.journalIssn"
              :placeholder="t('common.inputTextPlaceholder') + t('studentPaper.fields.journalIssn')"
              :disabled="!manualInput"
            />
          </el-form-item>
        </el-descriptions-item>
        <el-descriptions-item
          label-class-name="negative-warning-label"
          class-name="negative-warning-content"
          v-if="formData.negative"
          :label="t('studentPaper.view.warning')"
        >
          <el-alert type="error" :closable="false">{{ formData.negativeMessage }}</el-alert>
        </el-descriptions-item>
        <!-- 分区 暂时隐藏 -->
        <el-descriptions-item v-if="false" :label="t('studentPaper.fields.journalDistrict')">
          <el-form-item prop="journalDistrict">
            <EditInput
              v-model="formData.journalDistrict"
              :placeholder="
                t('common.inputTextPlaceholder') + t('studentPaper.fields.journalDistrict')
              "
            />
          </el-form-item>
        </el-descriptions-item>
        <!-- 影响因子 暂时隐藏 -->
        <el-descriptions-item v-if="false" :label="t('studentPaper.fields.journalImpactFactor')">
          <el-form-item prop="journalImpactFactor">
            <EditInput
              v-model="formData.journalImpactFactor"
              :placeholder="
                t('common.inputTextPlaceholder') + t('studentPaper.fields.journalImpactFactor')
              "
            />
          </el-form-item>
        </el-descriptions-item>
        <el-descriptions-item
          v-show="manualInput"
          label-class-name="is--asterisk"
          :label="t('studentPaper.fields.retrievalStatus')"
        >
          <el-form-item prop="retrievalStatus">
            <EditDict
              :dict-type="DICT_TYPE.RESEARCH_RETRIEVAL_STATUS"
              v-model="formData.retrievalStatus"
              :placeholder="
                t('common.selectTextPlaceholder') + t('studentPaper.fields.retrievalStatus')
              "
              :disabled="!manualInput"
              :disable-function="disableFun"
            />
          </el-form-item>
        </el-descriptions-item>
        <el-descriptions-item
          label-class-name="is--asterisk"
          :label="t('studentPaper.fields.publicationStatus')"
        >
          <el-form-item prop="publicationStatus">
            <EditDict
              :dict-type="DICT_TYPE.RESEARCH_PUBLICATION_STATUS"
              v-model="formData.publicationStatus"
              :placeholder="
                t('common.selectTextPlaceholder') + t('studentPaper.fields.publicationStatus')
              "
              :input-tips="t('studentPaper.inputTips.publicationStatus')"
            />
          </el-form-item>
        </el-descriptions-item>
        <el-descriptions-item
          v-if="formData.publicationStatus === '已接收'"
          label-class-name="is--asterisk"
          :label="t('studentPaper.fields.acceptanceLetter')"
        >
          <el-form-item prop="acceptanceLetter" key="acceptanceLetter">
            <IMRUpload
              v-model="formData.acceptanceLetter"
              :file-type="['pdf']"
              :file-size="20"
              :limit="1"
              :disabled="!edit"
            />
          </el-form-item>
        </el-descriptions-item>
        <el-descriptions-item
          v-if="formData.publicationStatus === '已接收'"
          label-class-name="is--asterisk"
          :label="t('studentPaper.fields.receiveTime')"
        >
          <el-form-item prop="receiveTime" key="receiveTime">
            <EditDate
              v-model="formData.receiveTime"
              :placeholder="
                t('common.selectTextPlaceholder') + t('studentPaper.fields.receiveTime')
              "
            />
          </el-form-item>
        </el-descriptions-item>
        <el-descriptions-item
          v-if="formData.publicationStatus === '已在线'"
          label-class-name="is--asterisk"
          :label="t('studentPaper.fields.retrievalNumber')"
        >
          <el-form-item prop="retrievalNumber" key="retrievalNumber">
            <EditInput
              v-model="formData.retrievalNumber"
              :placeholder="
                t('common.inputTextPlaceholder') + t('studentPaper.fields.retrievalNumber')
              "
            />
          </el-form-item>
        </el-descriptions-item>
        <el-descriptions-item
          v-if="formData.publicationStatus === '已在线'"
          label-class-name="is--asterisk"
          :label="t('studentPaper.fields.onlineTime')"
        >
          <el-form-item prop="onlineTime" key="onlineTime">
            <EditDate
              v-model="formData.onlineTime"
              :placeholder="t('common.selectTextPlaceholder') + t('studentPaper.fields.onlineTime')"
            />
          </el-form-item>
        </el-descriptions-item>
        <el-descriptions-item
          v-if="formData.publicationStatus === '已发表'"
          label-class-name="is--asterisk"
          :label="t('studentPaper.fields.publicationNumber')"
        >
          <el-form-item prop="publicationNumber" key="publicationNumber">
            <EditInput
              v-model="formData.publicationNumber"
              :placeholder="
                t('common.inputTextPlaceholder') + t('studentPaper.fields.publicationNumber')
              "
              :input-tips="t('studentPaper.inputTips.publicationNumber')"
            />
          </el-form-item>
        </el-descriptions-item>
        <el-descriptions-item
          v-if="formData.publicationStatus === '已发表'"
          label-class-name="is--asterisk"
          :label="t('studentPaper.fields.publishTime')"
        >
          <el-form-item prop="publishTime" key="publishTime">
            <EditDate
              v-model="formData.publishTime"
              :placeholder="
                t('common.selectTextPlaceholder') + t('studentPaper.fields.publishTime')
              "
            />
          </el-form-item>
        </el-descriptions-item>
        <el-descriptions-item :label="t('studentPaper.fields.remark')">
          <el-form-item prop="remark">
            <EditInput
              v-model="formData.remark"
              type="textarea"
              maxlength="200"
              show-word-limit
              :rows="2"
              :placeholder="t('common.inputTextPlaceholder') + t('studentPaper.fields.remark')"
            />
          </el-form-item>
        </el-descriptions-item>
        <template v-if="type === 'edit'">
          <el-descriptions-item :label="t('studentPaper.fields.reviewStatus')">
            <el-tag v-if="formData.reviewStatus" type="primary"
              >{{ formData.reviewStatus }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item :label="t('studentPaper.fields.reviewTime')">
            {{ formatDate(formData.reviewTime) }}
          </el-descriptions-item>
        </template>
      </el-descriptions>
    </el-form>

    <template v-if="edit" #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading"
        >{{ t('common.ok') }}
      </el-button>
      <el-button @click="handleCancelClick">{{ t('common.cancel') }}</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { StudentPaperApi, StudentPaperVO } from '@/api/core/studentpaper'
import EditInput from '@/components/EditViewInput/EditInput.vue'
import EditDate from '@/components/EditViewInput/EditDate.vue'
import EditDict from '@/components/EditViewInput/EditDict.vue'
import IMRUpload from '@/components/IMRUpload/index.vue'
import { DICT_TYPE, StringDictDataType } from '@/utils/dict'
import PositiveJournalSelect from '@/views/core/positivejournals/components/PositiveJournalSelect.vue'
import { formatDate } from '@/utils/formatTime'
import { FormInstance } from 'element-plus'
import { PositiveJournalsApi, PositiveJournalsVO } from '@/api/core/positivejournals'
import _ from 'lodash-es'

/** 论文 表单 */
defineOptions({ name: 'StudentPaperForm' })

const edit = ref(false)
provide('editMode', edit)

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formData = ref<Partial<StudentPaperVO>>({})
const type = ref('edit')
const formRef = ref<FormInstance>()

const formRules = reactive({
  // 论文题目
  paperTitle: [
    {
      required: true,
      message: t('common.inputTextPlaceholder') + t('studentPaper.fields.paperTitle'),
      trigger: 'blur'
    }
  ],
  // 附件
  attachment: [
    {
      required: true,
      message: t('common.uploadText') + t('studentPaper.fields.attachment'),
      trigger: 'blur'
    }
  ],
  // 论文类型
  paperType: [
    {
      required: true,
      message: t('common.selectTextPlaceholder') + t('studentPaper.fields.paperType'),
      trigger: 'change'
    }
  ],
  // 第一作者姓名
  primaryAuthor: [
    {
      required: true,
      message: t('common.inputTextPlaceholder') + t('studentPaper.fields.primaryAuthor'),
      trigger: 'blur'
    }
  ],
  // 本人排名
  personalRanking: [
    {
      required: true,
      message: t('common.selectTextPlaceholder') + t('studentPaper.fields.personalRanking'),
      trigger: 'change'
    }
  ],
  // 署名单位中科大排名
  casRanking: [
    {
      required: true,
      message: t('common.selectTextPlaceholder') + t('studentPaper.fields.casRanking'),
      trigger: 'change'
    }
  ],
  // 署名单位金属所排名
  imrRanking: [
    {
      required: true,
      message: t('common.selectTextPlaceholder') + t('studentPaper.fields.imrRanking'),
      trigger: 'change'
    }
  ],
  // 期刊名称
  journalName: [
    {
      required: true,
      message: t('common.inputTextPlaceholder') + t('studentPaper.fields.journalName'),
      trigger: 'blur'
    }
  ],
  // 期刊号
  journalIssn: [
    {
      required: true,
      message: t('common.inputTextPlaceholder') + t('studentPaper.fields.journalIssn'),
      trigger: 'blur'
    }
  ],
  // 收录情况
  retrievalStatus: [
    {
      required: true,
      message: t('common.selectTextPlaceholder') + t('studentPaper.fields.retrievalStatus'),
      trigger: 'change'
    }
  ],
  // 录用或发表情况
  publicationStatus: [
    {
      required: true,
      message: t('common.selectTextPlaceholder') + t('studentPaper.fields.publicationStatus'),
      trigger: 'change'
    }
  ],
  // 接收时间
  receiveTime: [
    {
      required: true,
      message: t('common.selectTextPlaceholder') + t('studentPaper.fields.receiveTime'),
      trigger: 'change'
    }
  ],
  // DOI号
  retrievalNumber: [
    {
      required: true,
      message: t('common.inputTextPlaceholder') + t('studentPaper.fields.retrievalNumber'),
      trigger: 'blur'
    }
  ],
  // 在线时间
  onlineTime: [
    {
      required: true,
      message: t('common.selectTextPlaceholder') + t('studentPaper.fields.onlineTime'),
      trigger: 'change'
    }
  ],
  // 发表刊次
  publicationNumber: [
    {
      required: true,
      message: t('common.inputTextPlaceholder') + t('studentPaper.fields.publicationNumber'),
      trigger: 'blur'
    }
  ],
  // 发表时间
  publishTime: [
    {
      required: true,
      message: t('common.selectTextPlaceholder') + t('studentPaper.fields.publishTime'),
      trigger: 'change'
    }
  ]
})

const dataId = ref('')
/** 打开弹窗 */
const open = async (id?: string) => {
  formData.value = {}
  if (id) {
    dataId.value = id
    type.value = 'edit'
    // 修改
    edit.value = false
    dialogVisible.value = true
    formLoading.value = true
    try {
      formData.value = await StudentPaperApi.getStudentPaper(id)
      if (formData.value && !formData.value?.attachment) {
        formData.value.attachment = '[]'
      }
      // 初始化手动输入期刊状态
      manualInput.value = !!(formData.value.journalName && !formData.value.journalId)
    } finally {
      formLoading.value = false
    }
  } else {
    // 新增
    type.value = 'new'
    edit.value = true
    dialogVisible.value = true
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  try {
    await formRef.value?.validate()
  } catch {
    return
  }
  if (!formData.value.attachment || formData.value.attachment === '[]') {
    message.error(t('common.uploadText') + t('studentPaper.fields.attachment'))
    return
  }
  if (type.value === 'edit') {
    // 提交请求
    formLoading.value = true
    try {
      const data = formData.value as unknown as StudentPaperVO
      await StudentPaperApi.updateStudentPaper(data)
      message.success(t('common.updateSuccess'))
      edit.value = false
      dialogVisible.value = false
      // 发送操作成功的事件
      emit('success')
    } finally {
      formLoading.value = false
    }
  } else {
    // 新增
    formLoading.value = true
    try {
      const data = formData.value as unknown as StudentPaperVO
      await StudentPaperApi.createStudentPaper(data)
      message.success(t('common.createSuccess'))
      dialogVisible.value = false
      // 发送操作成功的事件
      emit('success')
    } finally {
      formLoading.value = false
    }
  }
}

// 选择期刊后自动带入其他字段
const journalSelected = async (item: PositiveJournalsVO) => {
  if (item) {
    formData.value.journalName = item.name
    formData.value.journalImpactFactor = item.impactFactor
    formData.value.journalDistrict = item.district
    formData.value.journalIssn = item.issn
    formData.value.retrievalStatus = 'SCI'

    const response = await PositiveJournalsApi.judgePositiveJournals(item.id)
    formData.value.negative = response.isNegative
    formData.value.negativeMessage = response.message
  } else {
    formData.value.journalName = undefined
    formData.value.journalImpactFactor = undefined
    formData.value.journalDistrict = undefined
    formData.value.journalIssn = undefined
    formData.value.retrievalStatus = undefined

    formData.value.negative = false
    formData.value.negativeMessage = undefined
  }
}

const disableFun = (option: StringDictDataType) => {
  return option.value === 'SCI'
}

const backData = ref<Partial<StudentPaperVO>>({})

const handleEdit = () => {
  if (type.value === 'edit') {
    backData.value = _.cloneDeep(formData.value)
    edit.value = true
  }
}

const handleCancelClick = () => {
  if (type.value === 'edit') {
    edit.value = false
    formData.value = _.cloneDeep(backData.value)
    backData.value = {}
  } else {
    dialogVisible.value = false
  }
}

const manualInput = ref(false)
const handleSwitchJournal = () => {
  manualInput.value = !manualInput.value

  formData.value.journalId = undefined
  formData.value.journalName = undefined
  formData.value.journalIssn = undefined
  formData.value.journalDistrict = undefined
  formData.value.journalImpactFactor = undefined
  formData.value.retrievalStatus = undefined
}

const handleJournalManualInput = () => {
  formData.value.journalId = ''
  formData.value.negative = false
  formData.value.negativeMessage = undefined
}
</script>

<style lang="scss" scoped>
:deep(.el-form-item) {
  margin-bottom: 0;
}

:deep(.is--asterisk) {
  &:after {
    content: '*';
    margin-left: 4px;
    color: var(--el-color-primary);
  }
}

:deep(.el-form-item__error) {
  top: 80%;
}

:deep(.negative-warning-label) {
  background: var(--el-color-error-light-9) !important;
  color: var(--el-color-error) !important;
  text-align: center !important;
  font-weight: 700 !important;
}

:deep(.negative-warning-content) {
  padding: 0 !important;
}

:deep(.el-form-item__error) {
  top: 24px;
}
</style>
